package cn.windy.samary.utils;

import is.tagomor.woothee.Classifier;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * request工具类
 */
public class RequestUtil {
    public static final String X_REQUESTED_WIDTH = "X-Requested-With";
    public static final String XML_HTTP_REQUEST = "XMLHttpRequest";

    private static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
    private static String realPath = "";

    @SuppressWarnings("unchecked")
    public static String getQueryStrings(HttpServletRequest request) {
        Enumeration<String> attributeNames = request.getAttributeNames();
        List<String> attributeNameList = new ArrayList<String>();

        // 取出所有attribute的name，但不包括currentUrl,requestUri
        while (attributeNames.hasMoreElements()) {
            String name = (String) attributeNames.nextElement();

            if ("javax.servlet.forward.servlet_path".equals(name)
                    || "javax.servlet.forward.request_uri".equals(name)
                    || "javax.servlet.forward.context_path".equals(name)
                    || "javax.servlet.forward.query_string".equals(name)
                    || "currentUrl".equals(name) || "requestUri".equals(name)
                    || "requestUrl".equals(name) || "total".equals(name)) {
                continue;
            }
            attributeNameList.add(name);
        }

        StringBuilder sb = new StringBuilder();
        Enumeration<String> parameters = request.getParameterNames();
        Vector<String> vc = new Vector<String>();
        while (parameters.hasMoreElements()) {
            String parameterName = parameters.nextElement();
            if ("offset".equals(parameterName)) {
                continue;
            }
            vc.addElement(parameterName);
            sb.append("&").append(parameterName).append("=")
                    .append(request.getParameter(parameterName));
        }

        for (int i = 0; i < attributeNameList.size(); i++) {
            String name = attributeNameList.get(i);
            Object obj = request.getAttribute(name);
            if (obj instanceof String) {
                if (!vc.contains(name)) {
                    sb.append("&").append(name).append("=")
                            .append((String) request.getAttribute(name));
                }
            }
        }
        return sb.toString();
    }

    public static String getBasePath() {
        return threadLocal.get();
    }

    public static void setBasePath(String basePath) {
        threadLocal.set(basePath);
    }

    public static String getRealPath() {
        return realPath;
    }

    protected static void setRealPath(String realPath1) {
        realPath = realPath1;
        realPath = realPath.replace("\\", "/");
    }

    public static String makeParamUrl(Map<String, String> map) {
        StringBuffer result = new StringBuffer();
        if (!ObjectUtils.isEmpty(map)) {
            for (String key : map.keySet()) {
                String value = map.get(key);
                if (StringUtils.hasText(result)) {
                    result.append("&").append(key).append("=").append(value);
                } else {
                    result.append("?").append(key).append("=").append(value);
                }
            }
        }
        return result.toString();
    }

    /**
     * 判断浏览器类型
     *
     * @param request HttpServletRequest
     * @return 浏览器类型
     */
    public static String getBrowser(HttpServletRequest request) {
        String agent = request.getHeader("User-agent");
        @SuppressWarnings("rawtypes")
        Map info = Classifier.parse(agent);
        return (String) info.get("name") + "  " + info.get("version");
    }

    /**
     * 判断操作系统类型
     *
     * @param request HttpServletRequest
     * @return 操作系统类型
     */
    public static String getOs(HttpServletRequest request) {
        String agent = request.getHeader("User-Agent");
        @SuppressWarnings("rawtypes")
        Map info = Classifier.parse(agent);
        return (String) info.get("os");
    }

    /**
     * 判断是否ajax请求.
     * 可以看到Ajax 请求多了个 x-requested-with ，可以利用它，
     * request.getHeader("x-requested-with"); 为 null，则为传统同步请求，为 XMLHttpRequest，则为Ajax 异步请求。
     *
     * @param request HttpServletRequest
     * @return 是否ajax请求.
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String xr = request.getHeader(X_REQUESTED_WIDTH);
        return (xr != null && XML_HTTP_REQUEST.equalsIgnoreCase(xr));
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (cookieName.equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
